// Generated using webpack-cli https://github.com/webpack/webpack-cli

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');

const isProduction = process.env.NODE_ENV == 'production';

// MiniCssExtractPlugin.loader webpack内部插件，把css-loader生成的js变成css文件
// 前者用于生产环境 后者用于开发环境
const stylesHandler = isProduction ? MiniCssExtractPlugin.loader : 'style-loader';


// 核心
const config = {
    entry: './src/index.js',  // 入口文件，一个页面对应一个入口
    cache: true,
    output: {
        path: path.resolve(__dirname, 'dist'),
    },
    devServer: { //dev server环境配置
        open: true,
        host: 'localhost',
    },
    plugins: [ //插件
        new HtmlWebpackPlugin({  // html打包
            template: 'index.html',
        }),
        // Add your plugins here
        // Learn more about plugins from https://webpack.js.org/configuration/plugins/
    ],
    module: { // 资源解析，编译
        rules: [
            {
                test: /\.(js|jsx)$/i,
                loader: 'babel-loader',
            },
            {
                test: /\.less$/i, // less 结尾的文件
                // less-loader 把less变成css文件
                // postcss是一个平台，需要插件
                use: [stylesHandler, 'css-loader', 'postcss-loader', 'less-loader'],
            },
            {
                test: /\.css$/i, // css 结尾的文件
                // css-loader 会把css文件变成webpack认识的js
                // style-loader 会把js变成style标签插入到页面中
                // postcss-lader 是一个编译平台
                use: [stylesHandler, 'css-loader', 'postcss-loader'],// 右向左编译
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
                type: 'asset',
            },

            // Add your rules for custom modules here
            // Learn more about loaders from https://webpack.js.org/loaders/
        ],
    },
};

// 返回配置
module.exports = () => {
    if (isProduction) {
        config.mode = 'production';
        
        config.plugins.push(new MiniCssExtractPlugin());
        
        
        config.plugins.push(new WorkboxWebpackPlugin.GenerateSW());
        
    } else {
        config.mode = 'development';
    }
    return config;
};
